#include "historyproductstandarditemmodel.h"

HistoryProductStandardItemModel::HistoryProductStandardItemModel(QObject *parent) : QStandardItemModel(parent)
{
    header<<"商品型号"
         <<"商品名称"
        <<"单位"
       <<"品牌"
      <<"企业名称"
     <<"历史单价"
    <<"修改价格";

    setHorizontalHeaderLabels(header);
}

bool HistoryProductStandardItemModel::setData(const QModelIndex &index, const QVariant &value, int role){
    if(index.column() != header.size()-1){
        return false;
    }

    HistoryProduct *historyPrduct = historyProducts[index.row()];

    double price = value.toDouble();

    if(price<0){
        price=0.0;
    }

    historyPrduct->historyPrice = price;

    return QStandardItemModel::setData(index, price, role);
}

QVariant HistoryProductStandardItemModel::data(const QModelIndex &index, int role) const{
    QVariant value = QStandardItemModel::data(index, role);

    //设置内容颜色
    if (role == Qt::TextColorRole && (index.column() == header.size()-1))
        return QVariant::fromValue(QColor(Qt::blue));
    return value;
}

void HistoryProductStandardItemModel::reset(){
    clear();
    historyProducts.clear();
    setHorizontalHeaderLabels(header);
}

void HistoryProductStandardItemModel::insertHistoryProduct(HistoryProduct &historyProduct){
    QList<QStandardItem*> rowData;

    Product *product = historyProduct.getProduct();

    rowData.append(new QStandardItem(product==nullptr?"":product->type));
    rowData.append(new QStandardItem(product==nullptr?"":product->name));
    rowData.append(new QStandardItem(product==nullptr?"":product->unit));
    rowData.append(new QStandardItem(product==nullptr?"":product->brand));
    rowData.append(new QStandardItem(historyProduct.targetCompany.companyName));
    rowData.append(new QStandardItem(QString::number(historyProduct.historyPrice, 'f', 2)));
    rowData.append(new QStandardItem(QString::number(historyProduct.historyPrice, 'f', 2)));

    appendRow(rowData);

    historyProducts.append(&historyProduct);
}

void HistoryProductStandardItemModel::insertHistoryProduct(QList<HistoryProduct*> historyProducts){
    for(HistoryProduct *historyProduct:historyProducts){
        insertHistoryProduct(*historyProduct);
    }
}

QList<HistoryProduct*> HistoryProductStandardItemModel::getEditedHistoryProducts(){
    QList<HistoryProduct*> res;

    for(int i=0; i<rowCount(); i++){
        QString historyPrice = item(i, 5)->text();
        QString newPrice = item(i, 6)->text();
        if(historyPrice != newPrice){
            res.append(historyProducts[i]);
        }
    }

    return res;
}
